package com.resto.scm.web;

import com.resto.common.dao.helper.DaoHelper;
import com.resto.common.dao.helper.GenerateJavaBeanOfTable;

import java.io.*;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CodeGenerateFromJavaTemp {


	public static final String SCM = "scm";
	public static final String SCM_FIRST_UPPER_CASE = "Scm";
	final  static  String BASE_PATH = "C:/0821/";
	final  static  String SERVER_PATH = "resto-scm/";
	final  static  String WEB_PATH = "resto-shop/";

	final static String DaoPath = BASE_PATH + SERVER_PATH +"resto-scm-server/src/main/java/com/resto/scm/web/dao/";
	final static String MapperPath = BASE_PATH + SERVER_PATH +"resto-scm-server/src/main/java/com/resto/scm/web/manager/";
	final static String DaoMapperPath = BASE_PATH + SERVER_PATH +"resto-scm-server/src/main/resources/temp/";
	final static String ServicePath = BASE_PATH + SERVER_PATH +"resto-scm-api/src/main/java/com/resto/scm/web/service/";
	final static String ServiceImpl = BASE_PATH + SERVER_PATH +"resto-scm-server/src/main/java/com/resto/scm/web/service/impl/";


	final static String TempPath = BASE_PATH + SERVER_PATH +"resto-scm-api/source-temps/";
	final static String ModelClassName = BASE_PATH + SERVER_PATH +"resto-scm-api/src/main/java/com/resto/scm/web/model/";
	final static String ModelClassPackage="com.resto.scm.web.model";
	final static String DaoClassPackage="com.resto.scm.web.dao.";

	final static String JspPath = BASE_PATH + WEB_PATH +"resto-shop-web/src/main/webapp/WEB-INF/views/";
	final static String ControllerPath = BASE_PATH + WEB_PATH +"resto-shop-web/src/main/java/com/resto/shop/web/controller/scm/";

	static String classpath = CodeGenerateFromJavaTemp.class.getResource("/").getFile();

	public static void main(String[] args) throws Exception {

		/**
		 * arr [classSimpleName,idType,tableName]
		 * 实体类型 主键  和  表名
		 */
		String [][]  classPrimay = new String[][]{
			//new String[]{"DocPmsPoHeader","Long","doc_pms_po_header"},
			//new String[]{"DocPmsPoDetail","Long","doc_pms_po_detail"},
			new String[]{"MdBill","Long","md_bill"},

		};

		for (String[] cp: classPrimay) {
			String modelName = cp[0];
			if(modelName==null){
				continue;
			}
			String primaryKey = cp[1];
			String tableName = cp[2];
            //生成实体
			GenerateJavaBeanOfTable.getEntityOfTable(tableName,ModelClassName);
			Class<?> modelClass = null;
			try {
				modelClass= Class.forName(ModelClassPackage+"."+modelName);
				//生成jsp
				generaterJspFile(modelClass);
			}catch (Exception e){
				System.out.println(e.getMessage()+e.getStackTrace());
			}
			String mapperDir = DaoMapperPath+modelName+"Dao.xml";
			// 生成实体Dao
			generaterDaoFile(modelName,  primaryKey);
			Class<?> daoClass = null;
			try {
				//获取接口的class
				//daoClass =CodeGenerateFromJavaTemp.class.getClassLoader().loadClass(DaoClassPackage+modelName+"Dao");
				daoClass = Class.forName(DaoClassPackage+modelName+"Dao");
				//生成实体生成mapper.xml
				DaoHelper.genXMLWithFeature(mapperDir,daoClass, modelClass, tableName,true);
			}catch (Exception e){
				e.getStackTrace();
			}
			//生成实体生成mapper.java
			generaterMapperFile(modelName,primaryKey,tableName);
			generaterControllerFile(modelName,primaryKey);
			/**
			 * 生成 service 和 impl
			 */
			generaterServiceAndImpl(modelName,primaryKey);


		}
	}

	private static void generaterMapperFile(String modelName, String primaryKey,String tableName)throws IOException {
		String mapperTempPathFile =TempPath+"mapper.javat";
		String fileName = modelName+"Manager.java";
		boolean isOverWrite = true;
		Map<String,String> data = new HashMap<String,String>();
		data.put("modelName", modelName);
		data.put("primaryKey", primaryKey);
		data.put("modelNameLower", GenerateJavaBeanOfTable.toLowerCaseFist(modelName));
		data.put("tableName",tableName);
		generater(mapperTempPathFile,MapperPath+fileName,false,data);

	}

	private static String[][] getModelClass() throws ClassNotFoundException {
		File file = new File(ModelClassName);
		File[] fileList = file.listFiles();
		String [][]  classPrimay = new String [fileList.length][3];
		for(int i=0;i<fileList.length;i++){
			File f = fileList[i];
			String className = ModelClassPackage+"."+f.getName().substring(0,f.getName().length()-5);
			Class<?> clazz = Class.forName(className);
			try {
				String classSimpleName = clazz.getSimpleName();
				String idType = clazz.getDeclaredField("id").getType().getSimpleName();
				String tableName = getTableName(classSimpleName,"tb");
				String []  string = new String[]{classSimpleName,idType,tableName};
				classPrimay[i]=string;
			} catch (NoSuchFieldException | SecurityException e) {
				e.printStackTrace();
			}
		}
		return classPrimay;
	}

	private static String getTableName(String classSimpleName, String before) {
		StringBuffer b = new StringBuffer();
		b.append(before);
		for(char c:classSimpleName.toCharArray()){
			if(c>='A'&&c<='Z'){
				String add_ = "_"+c;
				b.append(add_.toLowerCase());
			}else{
				b.append(c);
			}
		}
		return b.toString();
	}

	private static void generaterJspFile(Class<?> className) throws IOException {
		
		String modelNameLower = SCM_FIRST_UPPER_CASE+className.getSimpleName();
		String jspTempFilePath = TempPath+"list-temp.jspt";
		
		String targetFilePath = JspPath+GenerateJavaBeanOfTable.toLowerCaseFist(modelNameLower)+"/list.jsp";
		Field[] f = className.getDeclaredFields();

		Map<String,String> map = new HashMap<String,String>();
		String [] ignoreField = new String[]{
				"id","createTime","creater_id","creater_name",
				"gmt_create","updater_id","updater_name","gmt_modified","is_delete"
		};

		StringBuffer formBody = new StringBuffer();
		StringBuffer columnObj = new StringBuffer();

		StringBuffer messageObj = new StringBuffer();
		StringBuffer saveObj = new StringBuffer();
		StringBuffer dataObj = new StringBuffer();
		int count =1;
		for (Field field : f) {
			String fieldName = field.getName();
			if(Arrays.asList(ignoreField).contains(fieldName)){
				continue;
			}
			String temp = "<div class=\"form-group\">\n"+
						  "    <label>{{name}}</label>\n"+
						  "    <input type=\"text\" class=\"form-control\" name=\"{{name}}\" v-model=\"m.{{name}}\">\n"+
						  "</div>\n";
			Map<String,String> data = new HashMap<String,String>();
			data.put("name", fieldName);
			String formGroup = readLineParam(temp, data);
			formBody.append(formGroup);
			
			String columnsTemp = "{                 \n"+
								 "	title : \"{{name}}\",\n"+
								 "	data : \"{{name}}\",\n"+
								 "},                 \n";
			String columnsGroup = readLineParam(columnsTemp, data);
			columnObj.append(columnsGroup);

			String savObjTemp ="saveObj.{{name}}=this.parameter.{{name}};\n";
			String savObjTempOfEach = readLineParam(savObjTemp, data);
			saveObj.append(savObjTempOfEach);

			String messageObjTemp1 ="if(!this.m.{{name}}) message='{{name}}';\n";
			String messageObjTemp2 ="else if(!this.m.{{name}}) message='{{name}}';\n";
			if(count ==1){
				String messageObjTempOfEach1  = readLineParam(messageObjTemp1, data);
				 messageObj.append(messageObjTempOfEach1);
			}else{
				String messageObjTempOfEach2 = readLineParam(messageObjTemp2, data);
				messageObj.append(messageObjTempOfEach2);
			}

			String dataObjTemp ="{{name}}: '',\n";
			String dataObjTempOfEach = readLineParam(dataObjTemp, data);
			dataObj.append(dataObjTempOfEach);


		}

		map.put("modelNameLower", GenerateJavaBeanOfTable.toLowerCaseFist(modelNameLower));
		map.put("formBody", formBody.toString());
		map.put("columnObj", columnObj.toString());
		map.put("messageObj", messageObj.toString());
		map.put("dataObj", dataObj.toString());
		map.put("saveObj", saveObj.toString());
		generater(jspTempFilePath, targetFilePath, false, map);

		count++;
	}

	public static void generaterDaoFile(String modelName, String primaryKey) throws Exception {
		String controllerTempFile =TempPath+"dao.javat";
		String fileName = modelName+"Dao.java";
		boolean isOverWrite = true;
		Map<String,String> data = new HashMap<String,String>();
		data.put("modelName", modelName);
		data.put("primaryKey", primaryKey);
		data.put("modelNameLower", GenerateJavaBeanOfTable.toLowerCaseFist(modelName));
		generater(controllerTempFile, DaoPath+fileName,false, data);
	}

	
	public static void generaterControllerFile(String modelName, String primaryKey) throws Exception {
		String controllerTempFile =TempPath+"controller-temp.javat";
		String fileName = SCM_FIRST_UPPER_CASE+modelName+"Controller.java";
		boolean isOverWrite = true;
		Map<String,String> data = new HashMap<String,String>();
		data.put("modelName", modelName);
		data.put("primaryKey", primaryKey);
		data.put("modelNameLower", GenerateJavaBeanOfTable.toLowerCaseFist(modelName));
		generater(controllerTempFile, ControllerPath+fileName,false, data);
	}


	
	
	public static void generaterServiceAndImpl(String modelName,String primaryKey) throws Exception {
		String serviceInterfaceTempFilePath = TempPath+"service-temp.javat";
		String serviceImplementTempFilePath = TempPath+"service-impl-temp.javat";
		String targetPackage = "com.resto.shop.web.service";
		String targetPackageImpl = "com.resto.shop.web.service.impl";
		String targetFileName = modelName+"Service.java";
		String targetFileNameImpl = modelName+"ServiceImpl.java";
		boolean isOverWrite = true;
		Map<String,String> data = new HashMap<String,String>();
		data.put("modelName", modelName);
		data.put("primaryKey", primaryKey);
		data.put("modelNameLower", GenerateJavaBeanOfTable.toLowerCaseFist(modelName));
		generater(serviceInterfaceTempFilePath, ServicePath+targetFileName,false, data);
		generater(serviceImplementTempFilePath, ServiceImpl+targetFileNameImpl,false, data);
		
	}


	


	
	public static void generater(String tempFilePath,String targetPath,boolean isOverWrite,Map<String,String> data) throws IOException{
		File tempFile = new File(tempFilePath);
		File targetFile = new File(targetPath);
		if(tempFile.exists()){
			if(targetFile.exists()&&!isOverWrite){
				System.err.println("文件已存在！"+targetFile.getAbsolutePath());
			}else if(isOverWrite&&targetFile.exists()){
				targetFile.delete();
				targetFile.createNewFile();
			}else{
				if(!targetFile.getParentFile().exists()){
					targetFile.getParentFile().mkdirs();
				}
				targetFile.createNewFile();
			}
			BufferedReader reader = new BufferedReader(new FileReader(tempFile));
			BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile));
			tempFileComplier(reader,writer,data);
		}else{
			System.err.println("模板文件不存在！"+tempFile.getAbsolutePath());
		}
	}

	private static void tempFileComplier(BufferedReader reader, BufferedWriter writer, Map<String, String> data) throws IOException {
		String line = "";
		while((line=reader.readLine())!=null){
			String lineRepalce = readLineParam(line,data);
			String lineRepalce2=lineRepalce = readLineParam2(lineRepalce,data);
			System.out.println(lineRepalce2);
			writer.write(lineRepalce2+"\n");
			writer.flush();
		}
		writer.close();
	}


	/**
	 *
	 * 2.{{name}} 匹配------》》》xxxxx
	 * @param line
	 * @param data
	 * @return
	 */
	private static String readLineParam(String line, Map<String, String> data) {
		Pattern pattern = Pattern.compile("\\{\\{[\\w]{0,}\\}\\}");
		Matcher m = pattern.matcher(line);
		while(m.find()){
			String mp = m.group();
			String key = mp.substring(2).substring(0, mp.length()-4);
			line = line.replace(mp, data.get(key)==null?"":data.get(key));
		}
		return line;
	}
	private static String readLineParam2(String line, Map<String, String> data) {
		Pattern pattern = Pattern.compile("\\[\\[[\\w]{0,}\\]\\]");
		Matcher m = pattern.matcher(line);
		while(m.find()){
			String mp = m.group();
			String key = mp.substring(2).substring(0, mp.length()-4);
			line = line.replace(mp, data.get(key)==null?"":data.get(key));
		}
		return line;
	}



}
